<!--
 * @Author: Liz.Zheng
 * @Date: 2022-01-05 13:31:58
 * @LastEditTime: 2023-02-15 17:42:48
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: iframe页面
 * @Motto: Write the code. Change the world.
-->
<template>
  <div class="iframe-box">
    <div class="option-bar">
      <div class="left">
        <a-space>
          <a-button
            type="text"
            @click="postRouteMessage('back')"
            :disabled="!iframeHistory.back"
          >
            <template #icon>
              <LeftOutlined />
            </template>
          </a-button>
          <a-button
            type="text"
            @click="postRouteMessage('forward')"
            :disabled="!iframeHistory.forward"
          >
            <template #icon>
              <RightOutlined />
            </template>
          </a-button>
          <a-button type="text" @click="refresh">
            <template #icon>
              <ReloadOutlined />
            </template>
          </a-button>
        </a-space>
      </div>
      <div class="middle">{{ iframeTitle || content.app_name }}</div>
      <div class="right"></div>
    </div>
    <iframe
      ref="iframeRef"
      :src="content.app_url"
      class="iframe"
      frameborder="no"
      border="0"
      marginWidth="0"
      marginHeight="0"
    ></iframe>
  </div>
</template>

<script>
import { defineComponent, watch, ref, nextTick, reactive, toRefs } from "vue";
import utils from "../../../../common/utils/utils";
import store from "../../../../store";
import {
  LeftOutlined,
  RightOutlined,
  ReloadOutlined,
} from "@ant-design/icons-vue";
import { useRoute, useRouter } from "vue-router";

export default defineComponent({
  name: "ApplicationIframePage",
  components: { LeftOutlined, RightOutlined, ReloadOutlined },
  props: {
    content: {
      type: Object,
      default: () => {
        return {};
      },
    },
    refresh: {
      type: Number,
      default: 0,
    },
    current: {
      type: [String, Number],
      default: "",
    },
  },
  setup(props, { emit }) {
    const route = useRoute();
    const router = useRouter();

    //   iframe实例
    const iframeRef = ref(null);

    const state = reactive({
      iframeHistory: {},
      iframeTitle: "",
    });

    // 刷新当前iframe
    const refresh = () => {
      if (props.content.app_micro) {
        iframeRef.value.contentWindow.postMessage({ type: "mainRefresh" }, "*");
      } else {
        iframeRef.value.src = props.content.app_url;
      }
      init();
    };

    // 与iframe通信
    const postMessage = () => {
      const data = {
        type: "mainMessage",
        from: "org",
        token: utils.getStorage("org_token"),
      };
      data.buildingInfo = JSON.stringify(store.getters.buildingInfo);
      data.userInfo = JSON.stringify(store.getters.userInfo);
      data.basicConfig = JSON.stringify(store.getters.basicConfig);
      data.tableConfig = JSON.stringify(store.getters.tableConfig);
      if (props.content.app_url.indexOf("?") != -1) {
        const paramsStr = props.content.app_url.split("?")[1];
        const paramsArr = paramsStr.split("&");
        let queryObj = {};
        for (let item of paramsArr) {
          const arr = item.split("=");
          queryObj[arr[0]] = arr[1];
        }
        data.query = queryObj;
      }
      iframeRef.value.contentWindow.postMessage(data, "*");
    };
    const getMessage = () => {
      window.onmessage = (e) => {
        console.log(e);
        const { type } = e.data;
        // 监听路由变化
        if (type === "urlChange") {
          state.iframeHistory = JSON.parse(e.data.history);
          state.iframeTitle = e.data.title;
        }
        // 打开其他子应用（以子应用方式打开，进入新页面）
        if (type === "toOtherApp") {
          const info = JSON.parse(e.data.info);
          utils.goAppRoute(info.app, info.name);
        }
        // 在当前页面打开其他子应用（以应用iframe方式打开）
        if (type === "toOtherIframe") {
          emit("open", {
            app: JSON.parse(e.data.appInfo),
          });
        }
        if (type === "toMainRoute") {
          router.push({ name: e.data.routeName });
        }
        if (type == "microSendMessage") {
          store.dispatch("setMicroSendMessage", e.data);
        }
        //子应用通知主应用弹出主应用的账单详情页面
        if (type == "showBillDetail") {
          store.commit("SET_SHOW_BILL_DETAIL_DRAWER", e.data.visible);
          store.commit("SET_BILL_ID", e.data.bill_id);
        }
        //子应用通知主应用弹出主应用的新建收支流水
        if (type == "addTurnover") {
          store.commit("SET_SHOW_ADD_TURNOVER", e.data.visible);
          store.commit("SET_ADD_TURNOVER_INFO", JSON.parse(e.data.record));
        }
        //子应用通知主应用弹出主应用的流水详情页面

        if (type == "showTurnoverDetail") {
          store.commit("SET_SHOW_TYRNOVER_DRAWER", e.data.visible);
          store.commit("SET_BILL_STREAM__ID", e.data.bill_stream_id);
        }
      };
    };
    const postRouteMessage = (type) => {
      if (state.iframeHistory[type]) {
        iframeRef.value.contentWindow.postMessage({ type }, "*");
      }
    };

    const init = () => {
      state.iframeHistory = {};
      nextTick(() => {
        iframeRef.value.onload = () => {
          postMessage();
          getMessage();
        };
      });
    };

    init();

    watch(
      () => props.refresh,
      (val) => {
        if (props.current == props.content.id) {
          // 刷新当前tab
          refresh();
        }
      }
    );
    return {
      iframeRef,
      ...toRefs(state),
      refresh,
      postRouteMessage,
    };
  },
});
</script>

<style lang="less" scoped>
.iframe-box {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #fff;
  .option-bar {
    width: 100%;
    height: 40px;
    display: flex;
    align-items: center;
    color: #333;
    border-bottom: 1px solid #ddd;
    overflow: hidden;
    padding: 0 20px;
    user-select: none;
    background: #f5f6f7;
    .left,
    .right {
      width: 200px;
      display: flex;
      align-items: center;
    }
    .middle {
      flex: 1;
      text-align: center;
      overflow: hidden;
    }
  }
  .iframe {
    width: 100%;
    height: calc(100% - 40px);
    overflow: hidden;
  }
}
</style>
